﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;


using DomainModel.Entities;
using DomainModel.Abstract;
using NHibernate.Criterion;


namespace DomainModel.Concrete
{
    public class PostsRepository : RepositoryBase, IPostsRepository
    {

        public IEnumerable<Post> GetAll()
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                ICriteria criteria = session.CreateCriteria(typeof(Post)).AddOrder(Order.Desc("PostID"));
                return criteria.List<Post>();
            }
        }


        public IEnumerable<Post> GetAll(bool isPublished)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                ICriteria criteria = session.CreateCriteria(typeof(Post)).AddOrder(Order.Desc("PostID"));
                return criteria.Add(Expression.Eq("IsPublished", isPublished)).List<Post>();
            }
        }

        public IEnumerable<Post> GetTop(int topNumber)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                ICriteria criteria = session.CreateCriteria(typeof(Post)).SetMaxResults(topNumber).AddOrder(Order.Desc("PostID"));
                return criteria.List<Post>();
            }
        }


        public Post Get(int? id)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                return session.Get<Post>(id);
            }
        }

        public void Save(Post item)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                session.SaveOrUpdate(item);
                session.Flush();
            }
        }

        public void Delete(int id)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                session.Delete(Get(id));
                session.Flush();
            }
        }
        


    }
}
